package com.davidlife.security.digitaldigest;

import com.davidlife.security.binarycodingstr.HexCoding;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Digest {

    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String message = "hello, i am davidlife, good night!";
        System.out.println("使用JDK自带的MD5: " + md5ByJdk(message));

        System.out.println("使用Apache 的MD5: " + md5ByApache(message, ""));

        System.out.println("使用Spring 的MD5: " + md5BySpring(message));
    }

    //盐，用于混交md5
    private static final String slat = "&%5123***&&%%$$#@";

    //JDK 自带的MD5使用方法
    public static String md5ByJdk(String message) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytes = md.digest(message.getBytes("utf8"));
        return HexCoding.bytes2HexString(bytes);
    }

    /**
     * 使用apache的commons-codec中的DigestUtils
     *
     * @param text 明文
     * @param key 密钥，即加的盐
     * @return 密文
     * @throws Exception
     */
    public static String md5ByApache(String text, String key) {
        //加密后的字符串
        String encodeStr= org.apache.commons.codec.digest.DigestUtils.md5Hex(text + key);
        return encodeStr;
    }

    public static String md5BySpring(String text) throws UnsupportedEncodingException {
//        String base = text + "/" + slat;
        //加密后的字符串
        String encodeStr = org.springframework.util.DigestUtils.md5DigestAsHex(text.getBytes("utf8"));
        return encodeStr;
    }

}
